﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TMI85303.Utils
{
    internal class JSONHelper
    {
        //把对象保存到指定文件
        public static bool WriteJSON<T>(T obj, string filePath)
        {
            string jsonstring = EntityToJSON(obj);
            if (jsonstring == string.Empty) { return false; }

            try
            {
                if (string.IsNullOrEmpty(filePath)) return false;
                string directory = Path.GetDirectoryName(filePath);

                // 创建目录（如果不存在）
                Directory.CreateDirectory(directory);
                using FileStream fs = new(filePath, FileMode.Create, FileAccess.ReadWrite);
                using StreamWriter sw = new(fs, Encoding.Default);
                sw.WriteLine(jsonstring);
            }
            catch (Exception)
            {
                return false;
            }
            return true;
        }

        //从指定的文件读取并生成指定对象
        public static bool ReadJSON<T>(string? filePath, out T obj)
        {
            obj = default;
            if (!File.Exists(filePath)) return false;

            try
            {
                using FileStream fs = new(filePath, FileMode.Open);
                using StreamReader sr = new(fs, Encoding.Default);
                obj = JSONToEntity<T>(sr.ReadToEnd());
                if (obj == null) return false;
            }
            catch (Exception)
            {
                return false;
            }
            return true;
        }

        /// <summary>
        /// 实体对象转换成JSON字符串,支持多态
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="x"></param>
        /// <returns></returns>
        public static string EntityToJSON<T>(T x)
        {
            string result = string.Empty;
            try
            {
                result = JsonConvert.SerializeObject(x, Formatting.Indented, new JsonSerializerSettings
                {
                    TypeNameHandling = TypeNameHandling.All,
                    NullValueHandling = NullValueHandling.Ignore
                });
            }
            catch (Exception)
            {
                result = string.Empty;
            }
            return result;
        }

        /// <summary>
        /// JSON字符串转换成实体类,支持多态
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="json"></param>
        /// <returns></returns>
        public static T JSONToEntity<T>(string json)
        {
            T t = default;
            try
            {
                //t = (T)JsonConvert.DeserializeObject(json, typeof(T));
                t = JsonConvert.DeserializeObject<T>(value: json, new JsonSerializerSettings
                {
                    TypeNameHandling = TypeNameHandling.All,
                    NullValueHandling = NullValueHandling.Ignore
                });
            }
            catch (Exception)
            {
                t = default;
            }
            return t;
        }


    }
}
